<script setup lang="ts">
import { ref, onMounted } from "vue";
import { useRouter } from "vue-router";
import { invoke } from "@tauri-apps/api/core";
import { debug } from "@tauri-apps/plugin-log";

const router = useRouter();

// 订单接口定义
interface Order {
    id: number;
    material_id: number;
    client_id: number;
    contact_id: number;
    quantity: number;
    price: number;
    amount: number;
    unit: string;
    place_order_date: string;
    plan_delivery_date: string;
    actual_delivery_date: string | null;
    status: number;
    remark: string;
    image_path: string | null;
    created_at: string;
    created_by: string;
    modified_at: string;
    modified_by: string;
    customer_name: string | null;
    customer_code: string | null;
    material_name: string | null;
    material_code: string | null;
    contact_name: string | null;
}

// 分页数据结构
interface Pagination<T> {
    page_size: number;
    page_total: number;
    page_current: number;
    page_items: T[];
}

// API响应接口
interface ApiResponse<T> {
    status_code: number;
    error_code: number;
    message: string;
    data: T | null;
}

// 查询条件
const searchParams = ref({
    customer_name: "",
    customer_code: "",
    material_code: "",
    contact: "",
    created_date: "",
    order_status: null as number | null,
    page_current: 1, // 当前页码，从1开始
    page_size: 20, // 每页大小
});

// 分页数据
const paginationData = ref<Pagination<Order> | null>(null);

// 状态下拉框选项
const statusOptions = [
    { value: 0, label: "作废" },
    { value: 1, label: "意向订单" },
    { value: 2, label: "已审核" },
    { value: 3, label: "排期" },
    { value: 4, label: "生产计划" },
    { value: 5, label: "生产中" },
    { value: 6, label: "生产完成未检查" },
    { value: 7, label: "生产完成未发货" },
    { value: 8, label: "已发货" },
    { value: 9, label: "投诉处理" },
    { value: 10, label: "完成" },
    { value: 11, label: "客户取消" },
    { value: 12, label: "退货" },
    { value: 13, label: "退货完成" },
    { value: 14, label: "索赔" },
];

var orderinfo = ref<Order | null>(null);
var orders = ref<Order[]>([]);
const loading = ref(false);
const error = ref("");

// 通过路由定义中的path直接匹配
function orderDetail(order: Order) {
    console.log(order);
    router.push("/ordernew/" + order.id);
}

function createOrder() {
    console.log("Creating order...");
    router.push("/ordernew");
}

function editOrder(order: Order) {
    orderinfo.value = order;
    console.log(orderinfo.value);
    router.push("/ordernew/" + order.id);
}

// 获取订单列表
async function fetchOrders() {
    loading.value = true;
    error.value = "";

    debug(`fetch order status: ${searchParams.value.order_status}`);

    try {
        const response: ApiResponse<Pagination<Order>> = await invoke(
            "list_order",
            {
                customer_name: searchParams.value.customer_name || null,
                customer_code: searchParams.value.customer_code || null,
                material_code: searchParams.value.material_code || null,
                contact: searchParams.value.contact || null,
                created_date: searchParams.value.created_date || null,
                order_status: searchParams.value.order_status || null,
                page_current: searchParams.value.page_current,
                page_size: searchParams.value.page_size,
            },
        );

        if (response.status_code === 200 && response.data) {
            paginationData.value = response.data;
            orders.value = response.data.page_items;
        } else {
            error.value = response.message || "获取订单列表失败";
            orders.value = [];
            paginationData.value = null;
        }
    } catch (err) {
        error.value = "网络请求失败";
        console.error("获取订单列表失败:", err);
        orders.value = [];
        paginationData.value = null;
    } finally {
        loading.value = false;
    }
}

// 搜索订单
function searchOrders() {
    searchParams.value.page_current = 1; // 搜索时重置到第一页
    fetchOrders();
}

// 重置搜索条件
function resetSearch() {
    searchParams.value = {
        customer_name: "",
        customer_code: "",
        material_code: "",
        contact: "",
        created_date: "",
        order_status: null,
        page_current: 1,
        page_size: 20,
    };
    fetchOrders();
}

// 改变页码
function changePage(page: number) {
    if (
        page < 1 ||
        (paginationData.value && page > paginationData.value.page_total)
    ) {
        return;
    }
    searchParams.value.page_current = page;
    fetchOrders();
}

// 改变每页大小
function changePageSize(size: number) {
    searchParams.value.page_size = size;
    searchParams.value.page_current = 1; // 改变页大小时回到第一页
    fetchOrders();
}

// 生成页码数组（用于分页控件显示）
function getPageNumbers() {
    if (!paginationData.value) return [];

    const current = paginationData.value.page_current;
    const total = paginationData.value.page_total;
    const pages = [];

    // 总是显示第一页
    pages.push(1);

    // 当前页前后的页面
    const start = Math.max(2, current - 2);
    const end = Math.min(total - 1, current + 2);

    // 添加省略号逻辑
    if (start > 2) pages.push("...");

    for (let i = start; i <= end; i++) {
        pages.push(i);
    }

    if (end < total - 1) pages.push("...");

    // 总是显示最后一页
    if (total > 1) pages.push(total);

    return pages;
}

// 根据状态值获取徽章样式
function getStatusBadgeClass(statusValue: number): string {
    const statusClasses: Record<number, string> = {
        0: "badge-error",
        1: "badge-info",
        2: "badge-success",
        3: "badge-warning",
        4: "badge-primary",
        5: "badge-secondary",
        6: "badge-accent",
        7: "badge-neutral",
        8: "badge-success",
        9: "badge-warning",
        10: "badge-success",
        11: "badge-error",
        12: "badge-warning",
        13: "badge-info",
        14: "badge-error",
    };

    return statusClasses[statusValue] || "badge-neutral";
}

// 获取状态标签
function getStatusLabel(statusValue: number): string {
    const status = statusOptions.find((opt) => opt.value === statusValue);
    return status ? status.label : "未知状态";
}

// 页面加载时初始化
onMounted(async () => {
    await fetchOrders();
});
</script>

<template>
    <main class="min-h-screen flex flex-col">
        <div class="flex-1 flex flex-col px-4">
            <div class="flex flex-col flex-1 relative">
                <!-- 加载状态 -->
                <div v-if="loading" class="text-center p-8">
                    <span class="loading loading-spinner loading-lg"></span>
                    <p class="mt-2">加载中...</p>
                </div>

                <!-- 错误信息 -->
                <div v-else-if="error" class="alert alert-error mb-6">
                    <svg
                        class="w-6 h-6"
                        aria-hidden="true"
                        xmlns="http://www.w3.org/2000/svg"
                        fill="none"
                        viewBox="0 0 24 24"
                    >
                        <path
                            stroke="currentColor"
                            stroke-linecap="round"
                            stroke-linejoin="round"
                            stroke-width="2"
                            d="M12 13V8m0 8h0m9-4a9 9 0 1 1-18 0 9 9 0 0 1 18 0Z"
                        />
                    </svg>
                    <span>{{ error }}</span>
                </div>

                <!-- 订单列表 -->
                <div v-else class="flex-1 flex flex-col">
                    <!-- 搜索和操作区域 -->
                    <div class="flex justify-between mb-4 py-4">
                        <div class="flex flex-wrap gap-2">
                            <input
                                v-model="searchParams.customer_name"
                                type="text"
                                placeholder="客户名称"
                                class="input input-bordered input-sm w-36"
                                @keyup.enter="searchOrders"
                            />

                            <input
                                v-model="searchParams.material_code"
                                type="text"
                                placeholder="材料代码"
                                class="input input-bordered input-sm w-20"
                                @keyup.enter="searchOrders"
                            />
                            <input
                                v-model="searchParams.contact"
                                type="text"
                                placeholder="联系人"
                                class="input input-bordered input-sm w-24"
                                @keyup.enter="searchOrders"
                            />
                            <input
                                v-model="searchParams.created_date"
                                type="date"
                                placeholder="创建时间"
                                class="input input-bordered input-sm w-36"
                            />

                            <!-- 状态下拉框 -->
                            <select
                                v-model="searchParams.order_status"
                                class="select select-bordered select-sm w-32"
                            >
                                <option :value="null">全部状态</option>
                                <option
                                    v-for="status in statusOptions"
                                    :key="status.value"
                                    :value="status.value"
                                >
                                    {{ status.label }}
                                </option>
                            </select>

                            <button
                                @click="searchOrders"
                                class="btn btn-sm btn-primary"
                            >
                                <svg
                                    class="w-4 h-4 text-white"
                                    aria-hidden="true"
                                    xmlns="http://www.w3.org/2000/svg"
                                    width="24"
                                    height="24"
                                    fill="none"
                                    viewBox="0 0 24 24"
                                >
                                    <path
                                        stroke="currentColor"
                                        stroke-linecap="round"
                                        stroke-width="2"
                                        d="m21 21-3.5-3.5M17 10a7 7 0 1 1-14 0 7 7 0 0 1 14 0Z"
                                    />
                                </svg>
                                搜索
                            </button>
                            <button
                                @click="resetSearch"
                                class="btn btn-sm btn-outline"
                            >
                                重置
                            </button>
                        </div>
                        <div class="flex gap-2">
                            <button
                                @click="createOrder()"
                                class="btn btn-sm btn-primary"
                            >
                                创建订单
                            </button>
                        </div>
                    </div>

                    <!-- 订单列表 -->
                    <div class="flex-1 overflow-auto mb-16">
                        <table class="table table-auto w-full">
                            <!-- head -->
                            <thead>
                                <tr class="bg-base-200 sticky top-0 z-10">
                                    <th class="w-12">
                                        <label>
                                            <input
                                                type="checkbox"
                                                class="checkbox checkbox-sm"
                                            />
                                        </label>
                                    </th>
                                    <th class="min-w-[120px]">客户</th>
                                    <th class="min-w-[120px]">材料</th>
                                    <th class="min-w-[100px]">颜色</th>
                                    <th class="min-w-[80px]">数量</th>
                                    <th class="min-w-[100px]">下单时间</th>
                                    <th class="min-w-[100px]">计划交付</th>
                                    <th class="min-w-[80px]">联系人</th>
                                    <th class="min-w-[80px]">单价</th>
                                    <th class="min-w-[80px]">总价</th>
                                    <th class="min-w-[100px]">状态</th>
                                    <th class="w-16">操作</th>
                                </tr>
                            </thead>
                            <tbody>
                                <tr
                                    v-for="(order, index) in orders"
                                    :key="index"
                                    @dblclick="orderDetail(order)"
                                    class="hover cursor-pointer"
                                >
                                    <td class="w-12">
                                        <label>
                                            <input
                                                type="checkbox"
                                                class="checkbox checkbox-sm"
                                            />
                                        </label>
                                    </td>
                                    <td class="min-w-[120px]">
                                        <div class="flex items-center gap-3">
                                            <div class="min-w-0 flex-1">
                                                <div class="font-bold truncate">
                                                    {{
                                                        order.customer_name ||
                                                        "未知客户"
                                                    }}
                                                </div>
                                            </div>
                                        </div>
                                    </td>
                                    <td class="min-w-[120px]">
                                        <div class="flex items-center gap-3">
                                            <div class="min-w-0 flex-1">
                                                <div class="font-bold truncate">
                                                    {{
                                                        order.material_name ||
                                                        "未知材料"
                                                    }}
                                                </div>
                                                <div
                                                    class="text-sm opacity-50 truncate"
                                                >
                                                    {{
                                                        order.material_code ||
                                                        "无代码"
                                                    }}
                                                </div>
                                            </div>
                                        </div>
                                    </td>
                                    <td class="min-w-[100px]">
                                        <div class="flex items-center gap-3">
                                            <div class="min-w-0 flex-1">
                                                <div
                                                    class="w-full h-6 rounded border mt-1 bg-gray-200"
                                                ></div>
                                            </div>
                                        </div>
                                    </td>
                                    <td class="min-w-[80px]">
                                        {{ order.quantity }}
                                    </td>
                                    <td class="min-w-[100px]">
                                        {{
                                            new Date(
                                                order.place_order_date,
                                            ).toLocaleDateString()
                                        }}
                                    </td>
                                    <td class="min-w-[100px]">
                                        {{
                                            new Date(
                                                order.plan_delivery_date,
                                            ).toLocaleDateString()
                                        }}
                                    </td>
                                    <td class="min-w-[80px] truncate">
                                        {{ order.contact_name || "无" }}
                                    </td>
                                    <td class="min-w-[80px] text-right">
                                        {{ order.price / 10000 }}
                                        {{ order.unit }}
                                    </td>
                                    <td class="min-w-[80px] text-right">
                                        {{ order.amount / 10000 }}
                                        {{ order.unit }}
                                    </td>
                                    <td class="min-w-[100px]">
                                        <span
                                            class="badge badge-sm"
                                            :class="
                                                getStatusBadgeClass(
                                                    order.status,
                                                )
                                            "
                                        >
                                            {{ getStatusLabel(order.status) }}
                                        </span>
                                    </td>
                                    <td class="w-16">
                                        <button
                                            class="btn btn-ghost btn-circle btn-xs"
                                            @click.stop="editOrder(order)"
                                        >
                                            <svg
                                                class="w-4 h-4 text-gray-800 dark:text-white"
                                                aria-hidden="true"
                                                xmlns="http://www.w3.org/2000/svg"
                                                width="24"
                                                height="24"
                                                fill="none"
                                                viewBox="0 0 24 24"
                                            >
                                                <path
                                                    stroke="currentColor"
                                                    stroke-linecap="round"
                                                    stroke-linejoin="round"
                                                    stroke-width="2"
                                                    d="m14.304 4.844 2.852 2.852M7 7H4a1 1 0 0 0-1 1v10a1 1 0 0 0 1 1h11a1 1 0 0 0 1-1v-4.5m2.409-9.91a2.017 2.017 0 0 1 0 2.853l-6.844 6.844L8 14l.713-3.565 6.844-6.844a2.015 2.015 0 0 1 2.852 0Z"
                                                />
                                            </svg>
                                        </button>
                                    </td>
                                </tr>
                            </tbody>
                        </table>

                        <!-- 空状态 -->
                        <div v-if="orders.length === 0" class="text-center p-8">
                            <p class="text-gray-500">暂无订单数据</p>
                        </div>
                    </div>
                    <!-- 订单列表 end -->
                </div>

                <!-- 固定在底部的分页控件 -->
                <div
                    v-if="paginationData"
                    class="fixed bottom-4 left-1/2 transform -translate-x-1/2 bg-base-100/80 backdrop-blur-sm rounded-lg shadow-lg p-4 z-10"
                >
                    <div class="flex items-center gap-4">
                        <!-- 每页大小选择 -->
                        <div class="flex items-center gap-2">
                            <span class="text-sm">每页:</span>
                            <select
                                :value="searchParams.page_size"
                                @change="
                                    changePageSize(
                                        Number(
                                            ($event.target as HTMLSelectElement)
                                                .value,
                                        ),
                                    )
                                "
                                class="select select-bordered select-sm w-20"
                            >
                                <option value="10">10</option>
                                <option value="20">20</option>
                                <option value="50">50</option>
                                <option value="100">100</option>
                            </select>
                        </div>

                        <!-- 分页按钮 -->
                        <div class="join">
                            <!-- 上一页 -->
                            <button
                                class="join-item btn btn-sm"
                                :class="{
                                    'btn-disabled':
                                        paginationData.page_current === 1,
                                }"
                                @click="
                                    changePage(paginationData.page_current - 1)
                                "
                            >
                                «
                            </button>

                            <!-- 页码按钮 -->
                            <button
                                v-for="page in getPageNumbers()"
                                :key="page"
                                class="join-item btn btn-sm"
                                :class="{
                                    'btn-active':
                                        page === paginationData.page_current,
                                    'btn-disabled': page === '...',
                                }"
                                @click="
                                    page !== '...' && changePage(Number(page))
                                "
                            >
                                {{ page }}
                            </button>

                            <!-- 下一页 -->
                            <button
                                class="join-item btn btn-sm"
                                :class="{
                                    'btn-disabled':
                                        paginationData.page_current ===
                                        paginationData.page_total,
                                }"
                                @click="
                                    changePage(paginationData.page_current + 1)
                                "
                            >
                                »
                            </button>
                        </div>

                        <!-- 页面信息 -->
                        <div class="text-sm">
                            第 {{ paginationData.page_current }} 页，共
                            {{ paginationData.page_total }} 页 (总共
                            {{ paginationData.page_items.length }} 条记录)
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </main>
</template>

<style scoped>
/* 表格样式优化 */
.table {
    table-layout: auto;
}

/* 悬停效果优化 */
.hover:hover {
    background-color: hsl(var(--b2) / 0.5);
}

/* 固定分页控件的背景模糊效果 */
.backdrop-blur-sm {
    backdrop-filter: blur(4px);
}

/* 表格单元格文本截断 */
.truncate {
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
}
</style>
